package com.katze.boot.applet.password.controller;

import com.alibaba.druid.filter.config.ConfigTools;
import com.katze.boot.applet.password.common.ICSRedisAESUtils;
import com.katze.boot.applet.password.entity.PasswordEntity;
import com.katze.boot.plugins.security.annotations.RestControllerMapping;
import com.katze.common.Message;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RestControllerMapping("/applet/password")
public class PasswordEncodedController {

    @RequestMapping(value = "/icsRedis", method = RequestMethod.POST)
    public Message redis(PasswordEntity entity) {
        if (StringUtils.isBlank(entity.getInput())) {
            return Message.ok();
        }
        if (entity.getOperate().equals("encrypt")) {
            return Message.ok().data(ICSRedisAESUtils.encrypt(entity.getInput()));
        } else if (entity.getOperate().equals("decrypt")) {
            return Message.ok().data(ICSRedisAESUtils.decrypt(entity.getInput()));
        }
        return Message.error("当前操作暂不支持");
    }

    @RequestMapping(value = "/druid", method = RequestMethod.POST)
    public Message druid(PasswordEntity entity) {
        if (StringUtils.isBlank(entity.getInput())) {
            return Message.ok();
        }
        try {
            StringBuilder builder = new StringBuilder();
            if (entity.getOperate().equals("encrypt")) {
                String[] arr = ConfigTools.genKeyPair(512);
                builder.append("私有密钥(privateKey):").append(arr[0]).append("\n");
                builder.append("公开密钥(publicKey):").append(arr[1]).append("\n");
                builder.append("密码(password):").append(ConfigTools.encrypt(arr[0], entity.getInput()));
                return Message.ok().data(builder.toString());
            } else if (entity.getOperate().equals("decrypt")) {
                return Message.ok().data(ConfigTools.decrypt(entity.getParams(), entity.getInput()));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error(entity.getOperate().equals("encrypt")? "加密":"解密" + "失败:" + e.getMessage());
        }
        return Message.error("当前操作暂不支持");
    }

    public static void main(String[] args) throws Exception {
        System.out.println(ConfigTools.decrypt("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAODI9a7Okouvxf90UB9+K+OPAZeDg/+Iu/v1ukHS1Gj6/9NGMsyzs+o5ivD5/CwZxBm+F5mb9a/U42/mTwdR0lsCAwEAAQ==", "J357ANo37SxAPDycV3LahYYtqEwwT0YpYvhbKuFLwJ/RvyTxbs7nA1t73D2rl6rYp7xUmc8RUY6WMFtIlkTf1g=="));
    }
}
